package com.kaixinff.kaixin001.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.kaixinff.kaixin001.util.Filter;
import com.kaixinff.kaixin001.util.KXClient;
import com.kaixinff.kaixin001.util.KXUtil;
import com.kaixinff.kaixin001.util.RegStep;
import com.kaixinff.name.User;

@SuppressWarnings("serial")
public class XWTeamServlet extends HttpServlet {
	private static final String INDEX_URL = KXUtil.HOST_URL + "/!spiderman/index.php";
	private int cid = 2;
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/html; charset=" + KXUtil.CHARSET);
		List<User> users = KXUtil.getUsers(new Filter(){
			@Override
			public boolean access(User user) {
				return user.hasStep(RegStep.ADD_XW);
			}}, resp);
		if (users == null) {
			return;
		}
		
		for (User user: users) {
			KXClient client = KXClient.getInstance(user.getId());
			String html = client.doGet(INDEX_URL, null).getContent();
			cid = getCid(html);
			doAppoint(client);
		}
	}
	
	public void doAppoint(KXClient client) throws IOException {
		String url = KXUtil.XW_URL + "/team.php";
		String html = client.doGet(url, null).getContent();
		Pattern p = Pattern.compile("<a href=\"team[.]php[?]uid=(\\d+?)&order=(.+?)\" class=\"sl2\">任命</a>");
		Matcher m = p.matcher(html);
		while (m.find()) {
			String uid = m.group(1);
			String order = m.group(2);
			boolean success = doAppoint(client, uid, order);
			if (!success) {
				return;
			}
		}
	}
	
	private boolean doAppoint(KXClient client, String uid, String order) throws IOException {
		String url = KXUtil.XW_URL + "/!team.php?uid=" + uid + "&order=" + order + "&flag=list&cid=" + cid + "&tmp=" + Math.random();
		while (url != null) {
			String html = client.doGet(url, null).getContent();
			Pattern p = Pattern.compile("onclick=\"doAppoint[(](\\d+?),(\\d+?)[)];\"");
			Matcher m = p.matcher(html);
			while (m.find()) {
				String fuid = m.group(1);
				String type = m.group(2);
				boolean result = false;
				try {
					result = doAppoint(client, uid, fuid, type);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				if (result) {
					return true;
				}
			}
			url = getNextPage(html, uid, order);
		}
		return true;
	}
	
	private String getNextPage(String html, String uid, String order) {
		Pattern p = Pattern.compile("<a href=\"team[.]php[?]uid=" + uid + "&order=" + order + "&start=(\\d+?)\" class=fy onfocus=\"this.blur[(][)];\">下一页");
		Matcher m = p.matcher(html);
		if (m.find()) {
			return KXUtil.XW_URL + "/team.php?uid=" + uid + "&order=" + order + "&start=" + m.group(1);
		}
		return null;
	}
	
	private boolean doAppoint(KXClient client, String uid, String fuid, String type) throws IOException, JSONException {
		String url = KXUtil.XW_URL + "/!ajax_appoint.php?fuid=" + fuid + "&type=" + type + "&flag=do&cid=" + cid + "&tmp=" + Math.random() + "&rt=json";
		String json = client.doGet(url, null).getContent();
		JSONObject jobj = new JSONObject(json);
		if (jobj.has("flag") && "confirm".equals(jobj.getString("flag"))) {
			url = KXUtil.XW_URL + "/!ajax_appoint.php?fuid=" + fuid + "&type=" + type + "&flag=do&confirm=1&cid=" + cid + "&tmp=" + Math.random() + "&rt=json";
			json = client.doGet(url, null).getContent();
			jobj = new JSONObject(json);
			if (jobj.has("flag") && "suc".equals(jobj.getString("flag"))) {
				String msg = KXUtil.findMessage(jobj.getString("html"));
				System.out.println(msg);
				return true;
			}
		}
		return false;
	}
	
	private int getCid(String html) {
		Pattern p = Pattern.compile("\"cid\"[:]\"(\\d+?)\"");
		Matcher m = p.matcher(html);
		if (m.find()) {
			return Integer.parseInt(m.group(1));
		}
		return 2;		
	}
}
